package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Resource
    private EmpService empService;

    @Override
    public PageResult<Clazz> clazzPage(String name, LocalDate begin, LocalDate end, int pageN, int pageSize) {
        Page<Clazz> clazzPage = new Page<Clazz>(pageN, pageSize);
        QueryWrapper<Clazz> wrapper = Wrappers.<Clazz>query()
                .like(name!=null && !"".equals(name),"name", name)
                .ge(begin!=null,"end_date", begin)
                .le(end!=null,"end_date", end);
        clazzPage = page(clazzPage,wrapper);
        List<Clazz> clazzes = clazzPage.getRecords();
        if(clazzes!=null && !clazzes.isEmpty()){
            //设置班主任
            Set<Integer> masterIds = clazzes.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toSet());
            if(!masterIds.isEmpty()){
                List<Emp> emps = empService.listByIds(masterIds);
                Map<Integer, String> map = emps.stream().collect(Collectors.toMap(Emp::getId, Emp::getName));
                clazzes.forEach(clazz->clazz.setMasterName(map.get(clazz.getMasterId())));
            }
            //设置开课状态
            clazzes.forEach(clazz->{
                LocalDate now = LocalDate.now();
                if(now.isBefore(clazz.getBeginDate())){
                    clazz.setStatus("未开课");
                }else if(now.isBefore(clazz.getEndDate())){
                    clazz.setStatus("已开课");
                }else{
                    clazz.setStatus("已结课");
                }
            });
            return new PageResult<>(clazzPage.getTotal(),clazzPage.getRecords());
        }
        return null;
    }
}
